//
//  ST_LikedPeculiarityViewController.swift
//  btvideo
//
//  Created by mac on 2020/1/10.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SnapKit
import MJRefresh
import SwifterSwift
import SwiftyUserDefaults


//喜欢特质列表
class ST_LikedPeculiarityViewController: ST_BTLightBarViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let title = ta.isEmpty ? "我喜欢的特质" : ta + "喜欢的特质"
        title_nav_btn.setTitleForAllStates(title)
        
         
        
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: 49+statusBarHeight, left: 0, bottom: 0, right: 0))
        }
        
        if title == "我喜欢的特质"{
            
            NotificationCenter.default.addObserver(self, selector: #selector(refresh_data), name: Notification.Name.like_peculiarity, object: nil)
            
            
        }
            
        request_data()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
//     MARK: - request_data
    var accid = ""
    
    var ta = ""
    
    fileprivate var currentPage = 0
    
    fileprivate lazy var displaySelf:Bool = {
//        为空 或者 ta == "我"
        if ta.isEmpty || ta == "我"{
            return true
        }else{
            return false
        }
    }()
    
    @objc fileprivate func refresh_data(){
        currentPage = 0
        request_data()
        
    }
    
    @objc fileprivate func request_data(){
        
        currentPage += 1
        
        var param = ["page":currentPage] as [String:Any]
        var api = PH.herIndexLikeFeatureListApi
        
        
        if displaySelf{
            api = PH.myIndexLikeFeatureListApi
        }
        
        param.updateValue(accid, forKey: "target_accid")
        
        JVrequest(api,parameters:param, success: { (json) in
            
            let dataStr = json["data"].rawString() ?? ""
            
            print("我或者她喜欢的特质：",json["data"].arrayValue.count)
            
            if let aArray = [ST_PairsPeculiarity].deserialize(from: dataStr) as? [ST_PairsPeculiarity]{
                
                if self.currentPage == 1{
                    self.data_array = aArray
                }else{
                    self.data_array += aArray
                }
                
                self.collectionView.reloadData()
                
//                self.loadMoreDataStyle(tableView: self.collectionView, count: aArray.count, pageSize: 20) {
//
//                    self.request_data()
//                }
                
            }else{
                self.collectionView.mj_footer?.endRefreshingWithNoMoreData()
                self.data_array.removeAll()
                self.collectionView.reloadData()
            }
            
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
            
        }) { (code, err) in
            
            ToastHud(text: err, view: self.view)
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
        }
    }

//     MARK: - Properties
    fileprivate lazy var cellSize:CGSize = {
       
        let w = (ScreenWidth - 15*4)/3
        
        var h = 15 + w + 33
        
        if !displaySelf{
           h += 5
        }
        
        return CGSize.init(width: w.int.cgFloat, height: h.int.cgFloat)
    }()

    fileprivate lazy var layout:UICollectionViewFlowLayout = {
       let controlLayout = UICollectionViewFlowLayout()
        controlLayout.minimumLineSpacing = 15
        if !displaySelf{
           controlLayout.minimumLineSpacing = 8
        }
        controlLayout.minimumInteritemSpacing = 15
        controlLayout.itemSize = cellSize
        controlLayout.sectionInset = UIEdgeInsets.init(top: 0, left: 15, bottom: BTSafeAreaBottom, right: 15)
        return controlLayout
    }()
    
    fileprivate lazy var collectionView:UICollectionView = {
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.delegate = self
        control.dataSource = self
        control.register(cellWithClass: ST_PeculiarityCell.self)
        control.register(cellWithClass: ST_PeculiarityAccordCell.self)
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.backgroundColor = Color.white
        
        control.alwaysBounceVertical = true
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        return control
    }()
    
    fileprivate var data_array = [ST_PairsPeculiarity]()
}


extension ST_LikedPeculiarityViewController:UICollectionViewDataSource,UICollectionViewDelegate{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        var cell:ST_PeculiarityCell!
            
//        其他人 有可能展示 我符合
        if !displaySelf{
            
            cell = collectionView.dequeueReusableCell(withClass: ST_PeculiarityAccordCell.self, for: indexPath)
            
        }else{
            cell = collectionView.dequeueReusableCell(withClass: ST_PeculiarityCell.self, for: indexPath)
        }
            
        
        if let m = data_array[safe:indexPath.item]{
            cell.model = m
        }
        
//        cell.backgroundColor = .random
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let curr = data_array[indexPath.row]
        
        
        /*
        let vcModel = ST_PeculiarityModel()
        
        vcModel.id = curr.id
        
        vcModel.name = curr.name
        
        if ta.isEmpty{
        
            if ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .female{
                vcModel.type = 1
            }else{
                vcModel.type = 2
            }
            
        }else{
            vcModel.type = (ta == "男") ? 1 : 2
        }
        
        vcModel.descriptionStr = curr.descriptionStr
        
//        vcModel.intro = curr.intro
        vcModel.image = curr.image
        */
        
        /*
            var own_num = 0
            var like_num = 0
            var sort = 0
            var pid = 0
            var create_time = ""
            var total = 0
        */
        
        
        
        var sameGender = true
        //     自己的话 这个地方展示异性特质
        if ta.contains("我"){
            sameGender = false
        }else if ta.contains("他") && ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .male{
            sameGender = false
        }else if ta.contains("她") && ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .female{
            sameGender = false
        }
        
        
        
        push_peculiarity(id: curr.id, onlyDisplayPerson: sameGender, navigationController: self.navigationController)
        
    }
    
    
    
}




//MARK: - 我符合Cell
class ST_PeculiarityAccordCell: ST_PeculiarityCell {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        cover_image_view.snp.updateConstraints { (make) in
            make.top.equalToSuperview()
        }
        
        contentView.addSubview(right_sign_view)
        right_sign_view.snp.makeConstraints { (make) in
            make.height.equalTo(20)
            make.width.equalTo(45+20)
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        
        right_sign_view.addSubview(right_sign_text_label)
        right_sign_text_label.snp.makeConstraints { (make) in
            make.right.equalToSuperview()
            make.centerY.equalToSuperview()
        }
        
        right_sign_view.addSubview(right_sign_corner_view)
        right_sign_corner_view.snp.makeConstraints { (make) in
            make.right.equalTo(right_sign_text_label.snp.left).offset(-5)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(6)
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    fileprivate lazy var right_sign_view:UIView = {
       let control = UIView()
        control.isHidden = true
        return control
    }()
    
    fileprivate lazy var right_sign_corner_view:UIView = {
       let control = UIView()
        control.backgroundColor = Color.init(hex: 0x42DAA3)
        control.cornerRadius = 3
        return control
    }()
    
    fileprivate lazy var right_sign_text_label:UILabel = {
       let control = UILabel()
        control.textColor = Color.init(hex: 0xACB4C0)
        control.text = "我符合！"
        control.font = UIFont.systemFont(ofSize: 12)
        return control
    }()
    
    override var model: ST_PairsPeculiarity{
        didSet{
            
            right_sign_view.isHidden = !model.is_conform
            
        }
    }
}
